#!/bin/sh
#
# see: dh_installdeb(1)

set -e

package="npm4-installer"

npm_pkg_install () {
	echo "${package}:installing:[${npm_file}]"
	if [ ! -d /usr/local/lib/node_modules/ ] ; then
		mkdir -p /usr/local/lib/node_modules/ || true
	fi
	if [ -d /usr/local/lib/node_modules/${npm_project}/ ] ; then
		rm -rf /usr/local/lib/node_modules/${npm_project}/ || true
	fi

	echo "${package}:updating:[/usr/local/lib/node_modules/${npm_project}/]"
	tar xf /var/cache/${package}/${npm_file} -C /usr/local/lib/node_modules/
}

npm_install () {
	node_bin="/usr/bin/nodejs"

	unset node_version
	node_version=$(/usr/bin/nodejs --version || true)
	echo "${package}:nodejs:[${node_version}]"

	v8="v8.9.1"

	node_red="npm-4.6.1"

	npm_project="npm"
	case "${node_version}" in
	v8.*)
		npm_file="${node_red}-${v8}.tar.xz"
		npm_pkg_install
		;;
	esac

	ln -sf /usr/local/lib/node_modules/${npm_project}/bin/npm-cli.js /usr/local/bin/npm4

	echo "${package}:Installed"
}

case "$1" in
    configure)
	npm_install
    ;;

    abort-upgrade|abort-remove|abort-deconfigure)
    ;;

    *)
        echo "postinst called with unknown argument \`$1'" >&2
        exit 1
    ;;
esac

# dh_installdeb will replace this with shell code automatically
# generated by other debhelper scripts.

#DEBHELPER#

exit 0

